package com.fushenlan.excel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author XUJIN
 * @DATE 2022/4/26
 * @PACKAGE_NAME com.fushenlan.excel
 * @VERSION 1.0
 */
public class ExportExcelUtil {

    /**
     * 导出excel
     *
     * @param list 数据集合
     * @param pojoClass 数据类型
     * @param fileName 文件名称
     * @param title 表明
     * @param response 响应对象
     */
    public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, String title, HttpServletResponse response) {

        ExportParams exportParams = new ExportParams(title, null);
        // 自定义字典查询规则
        //exportParams.setDictHandler(new ExcelSubHandler());
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String now = sdf.format(new Date());
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")+"-"+now +".xls");
                workbook.write(response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
